/**
 * 
 */
package org.bookie.framework.services.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.bookie.core.model.FacebookUser;
import org.bookie.core.services.IAuthenticationContext;
import org.bookie.core.services.IFacebookClient;
import org.bookie.framework.services.EmailEngine;
import org.bookie.framework.services.MessageManager;
import org.bookie.model.BetSlip;
import org.bookie.model.User;
import org.bookie.model.Wager;

/**
 * Implementation of the {@link MessageManager}
 * 
 * @author zubairov
 */
public class MessageManagerImpl implements MessageManager {

	private IFacebookClient client;

	private Log log;

	private IAuthenticationContext authenticationContext;

	private EmailEngine emailEngine;

	public MessageManagerImpl(IFacebookClient client,
			IAuthenticationContext ac, EmailEngine ee, Log log) {
		this.client = client;
		this.authenticationContext = ac;
		this.emailEngine = ee;
		this.log = log;
	}

	/**
	 * {@inheritDoc}
	 */
	public void betSlipPlaced(BetSlip betSlip) {
		log.debug("Notifying about new betslip was activated");
		if (client.isAuthenticated()) {
			List<Wager> bets = betSlip.getBets();
			for (Wager wager : bets) {
				try {
					FacebookUser user = client.getAuthenticatedUser();
					String label = wager.getOutcome().getBet().getEvent()
							.getLabel();
					Double ammount = wager.getOdds();
					String title = " bet on <b>" + label + "</b>";
					String body = "<fb:name uid=\"" + user.getId()
							+ "\"/> put " + ammount + " on "
							+ wager.getOutcome().getLabel();
					boolean result = client.publishAction(title, body);
					if (!result) {
						log.error("Publishing of the event from "
								+ user.getName()
								+ " failed due to permission denided");
					}
				} catch (Exception e) {
					log.debug("Exception during posting events on facebook", e);
				}
			}
		} else {
			log.debug("Current user has no Facebook authentication, "
					+ "sending email confirmation");
			User user = authenticationContext.getUser();
			emailEngine.sendEmail(user.getEmail(), "BetSlip",
					new Object[] { user.getUsername(), betSlip });

		}
	}

}
